package com.wiscamp.ninechapters.challenges.infrastructure.mappers;

import com.wiscamp.ninechapters.challenges.infrastructure.po.UserPointsMonthPO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;

@Repository
public interface UserPointsMonthMapper extends JpaRepository<UserPointsMonthPO, Long>, JpaSpecificationExecutor<UserPointsMonthPO> {
    /**
     * 按个人月度积分排名分页获取前100名用户月度积分列表
     *
     * @param pageable
     * @return
     */

    @Query(value = "select e from UserPointsMonthPO e where e.monthPoints > 0 and e.dateYear = :year and dateMonth = :month order by e.monthPoints desc")
    Page<UserPointsMonthPO> getTop100OrderByMonthPoints(int year, int month, Pageable pageable);


    //UserPointsMonth findByUserId(long userId);
    @Query(value = "select e from UserPointsMonthPO e where e.userId = :userId and e.dateYear = :year and e.dateMonth = :month order by e.monthPoints desc")
    UserPointsMonthPO findByUserIdAndDateYearAndDateMonth(long userId, int year, int month);

    @Modifying
    @Transactional
    @Query(nativeQuery = true, value = "update user_points_month e set e.month_rank = 999 where e.month_rank <= 100 and e.user_id not in (:userIds)")
    void rankingAfter100ByPoints(Collection<Long> userIds);
}